package com.uinnova.product.eam.web.diagram.bean.impt;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import com.binary.core.exception.MessageException;
import com.binary.core.util.BinaryUtils;

public class ProgressCatch{

	private static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();
	
	/**
	 * 添加进度
	 * @param key
	 * @param value
	 */
    public static void putProgress(String key, ProgressBean value){
    	verifyProgress(key);
        map.put(key, value);
    }
    
    /**
     * 添加进度
     * @param progress
     */
    public static void putProgress(ProgressBean progress) {
    	BinaryUtils.checkNull(progress.getKey(), "key");
		putProgress(progress.getKey(), progress);
	}
    
    /**
     * 获取进度
     * @param key
     * @return
     */
	public static ProgressBean getProgress(String key){
		ProgressBean progressBean = null;
		progressBean = (ProgressBean) map.get(key);
        return progressBean;
    }
	
    /**
     * 完成进度, 延时清理进度
     * @param key
     * @param timeOut 清理进度延时,单位:秒
     */
    public static void removeDelay(final String key,final Long timeOut){
    	ProgressUtil.ciImporting = false;
    	Object progressBean = map.get(key);
    	if(BinaryUtils.isEmpty(progressBean)) return;
    	if (null ==timeOut||0==timeOut) {
    		map.remove(key);
    		return;
		}
    	
    	TimerTask task = new TimerTask() {
			@Override
			public void run() {
				map.remove(key);
			}
		};
    	Timer timer = new Timer();
    	timer.schedule(task, timeOut*1000);
    }

    /**
     * 完成进度, 延时10s清理进度
     * @param key
     */
    public static void endProgress(String key){
    	removeDelay(key,10L);
    }
    
    /**
     * 结束进度,延时清理
     * @param progress
     * @param timeOut
     */
    public static void endProgress(ProgressBean progress, Long timeOut){
    	BinaryUtils.checkNull(progress.getKey(), "key");
    	removeDelay(progress.getKey(),timeOut);
    }
    
    /**
     * 结束进度,延时10s清理
     * @param progress
     */
    public static void endProgress(ProgressBean progress){
    	endProgress(progress,10L);
    }
    
    /**
     * 验证重复进度
     * @param key
     */
	private static void verifyProgress(String key) {
		ProgressBean progressResult = getProgress(key);
		if (!BinaryUtils.isEmpty(progressResult)) {
			throw MessageException.i18n("BS_MNAME_PROGRESS_EXISTS", "{\"key\":\" " + key + "\"}");
		}
	}
	
}